<template>
  <div class="adminRole">
    <el-form
      ref="formRef"
      :inline="true"
      :model="form"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]"
    >
      <el-form-item label="地图名称：" prop="name">
        <el-input
          v-model="form.name"
          placeholder="请输入地图名称"
          clearable
          class="!w-[200px]"
        />
      </el-form-item>
      <el-form-item label="状态：" prop="status">
        <el-select v-model="form.status" clearable>
          <el-option label="全部" :value="''" />
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon(Search)"
          :loading="loading"
          @click="onSearch"
        >
          搜索
        </el-button>
        <el-button :icon="useRenderIcon(Refresh)" @click="resetForm(formRef)">
          重置
        </el-button>
      </el-form-item>
    </el-form>

    <PureTableBar
      title="地图管理"
      :columns="columns"
      @refresh="onSearch"
      style="height: calc(100vh - 200px)"
    >
      <template #buttons>
        <!-- <el-button type="success" :icon="useRenderIcon(AddFill)" @click="pureMap.operateDrawer(true)">
          交管设置
        </el-button> -->

        <el-button
          type="primary"
          :icon="useRenderIcon(AddFill)"
          @click="openDialog()"
        >
          新增地图
        </el-button>

        <!-- 上传组件 -->
        <el-upload
          class="upload"
          accept=".xmap"
          :show-file-list="false"
          :http-request="uploadMap"
          ref="uploadRef"
        >
        </el-upload>
      </template>
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          ref="tableRef"
          adaptive
          align-whole="center"
          row-key="Id"
          showOverflowTooltip
          table-layout="auto"
          :loading="loading"
          :data="dataList"
          :columns="dynamicColumns"
          :header-cell-style="{
            background: 'var(--el-fill-color-light)',
            color: 'var(--el-text-color-primary)'
          }"
          @page-size-change="handleSizeChange"
          @page-current-change="handleCurrentChange"
        >
          <template #operation="{ row }">
            <el-button
              type="success"
              link
              :icon="useRenderIcon(Refresh)"
              @click="getMapID(row)"
              >导入地图</el-button
            >
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              :icon="useRenderIcon(EditPen)"
              @click="openDialog('编辑', row)"
            >
              编辑
            </el-button>
            <el-button
              class="reset-margin"
              link
              type="danger"
              :size="size"
              :icon="useRenderIcon(outlineDelete)"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </pure-table>

        <!-- 地图交管组件 -->
        <!-- <div class="mapCross">
          <div class="mapCorrd">
            <p>x:{{mouseCorrd.x}},y:{{mouseCorrd.y}}</p>
          </div>
          <div id="canvasMap" ref="map"></div>
        </div> --> 
      </template>
    </PureTableBar>

    <el-dialog
      v-model="centerDialogVisible"
      title="请选择导入类型"
      width="500"
      center
    >
      <div>
        <el-radio-group v-model="radio">
          <el-radio label="1" size="large">科聪地图</el-radio>
          <el-radio label="2" size="large">睿芯行地图</el-radio>
        </el-radio-group>
        <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="ruleForm"
          status-icon
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          v-show="radio === '2'"
        >
          <el-form-item label="AGV地址" prop="agvIP">
            <el-input
              v-model="ruleForm.agvIP"
              autocomplete="off"
              placeholder="例如：172.18.134.182"
            />
          </el-form-item>
          <el-form-item label="端口号" prop="port">
            <el-input
              v-model="ruleForm.port"
              autocomplete="off"
              placeholder="例如：8080"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="importMapSubmit(ruleFormRef)">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 抽屉 -->
    <!-- <el-drawer
      v-model="pureMap.crossSwitch"
      title="新增交管区域"
      direction="ltr"
      size="500px"
      :close-on-click-modal="true"
      :modal="false"
      modal-class="modalCross"
    >
      <el-alert title="可以通过双击右侧地图来添加交管坐标" type="warning" center :closable="false" style="margin-bottom:20px" />
      <crossForm :formInline="formInline" ></crossForm>
    </el-drawer> -->
  </div>
</template>

<script lang="ts" setup>
import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useDept } from "./utils/hook";
import { ref, onMounted, onUnmounted, reactive } from "vue";
import { message } from "@/utils/message";
import { ElMessageBox, FormInstance, FormRules } from "element-plus";
import x2js from "x2js";
import analysis from "./utils/analysisMap";
import { ImportMap } from "@/utils/api/dispatch/map";
import type { UploadInstance, UploadProps, UploadRawFile } from "element-plus";
import { initKonvaStage, mouseCorrd } from "@/views/home/components/dxfMap";
import { readFile } from "@/views/home/components/readFile";
import crossForm from "./crossForm.vue";
import { useMapStoreHook } from "@/store/modules/map";
import axios from "axios";
import convertData from "./utils/dataConversion";

// iconify-icons
import AddFill from "@iconify-icons/ri/add-circle-line";
import EditPen from "@iconify-icons/ep/edit-pen";
import outlineDelete from "@iconify-icons/ic/outline-delete";
import Search from "@iconify-icons/ep/search";
import Refresh from "@iconify-icons/ep/refresh";

async function fetchData() {
  try {
    const res = await axios.post(
      `http://${ruleForm.agvIP}:${ruleForm.port}/rbrainrobot/request_node_info`
    );
    if (res.data.msg === "ok") {
      let data = convertData(res, mapid.value);
      ImportMap(data).then(res => {
        if (res.Code === 0) {
          message(`地图文件导入成功`, {
            type: "success"
          });
        }
      });
    } else {
      message(`导入失败:${res.data.error_info}`, { type: "error" });
    }
  } catch (error) {
    message(`请求失败,找不到网址`, { type: "error" });
    console.error("Error fetching data:", error);
  }
}

const ruleFormRef = ref<FormInstance>();
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入AGV地址"));
  } else {
    if (ruleForm.port !== "") {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.validateField("port");
    }
    callback();
  }
};
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入端口号"));
  } else {
    callback();
  }
};

const ruleForm = reactive({
  agvIP: "",
  port: ""
});

const rules = reactive<any>({
  agvIP: [{ validator: validatePass, trigger: "blur" }],
  port: [{ validator: validatePass2, trigger: "blur" }]
});

const formRef = ref();
const uploadRef = ref<UploadInstance>();

var mapid = ref(null);
var map = ref();
const pureMap = useMapStoreHook();

var formInline = {
  name: "",
  status: 1,
  stationList: [{}],
  note: "",
  type: 1,
  stationids: []
};

// 对话框开关
const centerDialogVisible = ref(false);
// 单选框
let radio = ref("1");
// 导入地图
function getMapID(row: any) {
  mapid.value = row.id;
  if (row.import === 1) {
    ElMessageBox.confirm(
      `该地图已导入过地图文件，重复导入可能会导致任务异常，请确认是否依旧执行此操作！`,
      "提示",
      {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
        center: true
      }
    )
      .then(() => {
        centerDialogVisible.value = true;
        // uploadRef.value.$el.querySelector('input').click()
      })
      .catch(() => {});
  } else {
    centerDialogVisible.value = true;
    // uploadRef.value.$el.querySelector('input').click()
  }
}
// 对话框确定
const importMapSubmit = (formEl: FormInstance | undefined) => {
  if (radio.value === "1") {
    uploadRef.value.$el.querySelector("input").click();
    centerDialogVisible.value = false;
  } else if (radio.value === "2") {
    if (!formEl) return;
    formEl.validate(valid => {
      if (valid) {
        // console.log('submit!')
        fetchData();
        centerDialogVisible.value = false;
      } else {
        console.log("error submit!");
      }
    });
  }
};

// 导入地图
function uploadMap(options: any) {
  // 读取文件
  var file = options.file;
  // 创建FileReader对象
  const reader: any = new FileReader();
  // 以文本形式读取文件
  reader.readAsText(file);

  reader.onload = (e: any) => {
    // 将 XML 数据转换为 JSON 对象
    var x2jss = new x2js();
    // 将xml转换为js对象
    const xml = x2jss.xml2js(reader?.result);
    // 分析xml对象，获取数据
    const data = analysis(xml, mapid.value);
    // console.log("data=>", data);

    // 导入地图数据
    ImportMap(data).then(res => {
      // 如果导入成功
      if (res.Code === 0) {
        // 弹出成功提示
        message(`地图文件导入成功`, {
          type: "success"
        });
      }
    });
  };
}

// onMounted(()=>{
//   readFile().then(data => {
//     initKonvaStage('canvasMap', map, data, true)
//   })
// })

// onUnmounted(()=>{
//   pureMap.clearCross()
// })

const {
  columns,
  loading,
  dataList,
  openDialog,
  handleDelete,
  form,
  onSearch,
  resetForm,
  pagination,
  handleSizeChange,
  handleCurrentChange
} = useDept();
</script>

<style lang="scss" scoped>
.upload {
  display: inline-block !important;
  height: 20px;
  vertical-align: middle;
}

.search-form {
  :deep(.el-form-item) {
    margin-bottom: 12px;
  }
}

.mapCross {
  position: relative;
  height: calc(100% - 260px);
  background: linear-gradient(90deg, rgb(62 61 61 / 40%) 2%, transparent 0%) 0 0,
    linear-gradient(180deg, transparent 99%, rgb(62 61 61 / 40%) 1%) 0 0;
  background-color: #001529;
  background-size: 50px 50px;

  // #canvasMap {
  //     width: 100%;
  //     height: 100%;
  // }
}

.pure-table {
  height: 200px;
  overflow: hidden;
}
</style>
